Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
Is `if (idx < arr.length)` equivalent to `if (arr[idx])`?

Assuming that all elements inside an array have a value different from undefined, null or 0, is

if (idx < arr.length) equivalent to if (arr[idx])?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

No.

There are other falsy values that will evaluate to false in the if statement, such as an empty string (''):

const arrWithEmptyString = ['', '', ''];
const idx = 2;

console.log(!!(idx < arrWithEmptyString.length));
console.log(!!arrWithEmptyString[idx]);

Alternatively, what if the array contains a boolean false?

const boolArray = [true, false, true, false]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);

Type coercion/type conversion in JS can be confusing and unpredictable-- in my opinion it is generally better to be explicit and test exactly what it is you mean to test, rather than relying on weak type comparisons to save a few characters.

about 4 years ago · Juan Pablo Isaza Relatório

0

Nice answer from Alexander Nied, also NaN evaluates to false

const boolArray = [NaN, NaN, NaN, NaN]
const idx = 3;
console.log(!!(idx < boolArray.length));
console.log(!!boolArray[idx]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda